package org.sonar.samples.java.checks;

import org.sonar.check.Priority;
import org.sonar.check.Rule;
import org.sonar.plugins.java.api.IssuableSubscriptionVisitor;
import org.sonar.plugins.java.api.semantic.Symbol;
import org.sonar.plugins.java.api.semantic.Type;
import org.sonar.plugins.java.api.tree.MethodTree;
import org.sonar.plugins.java.api.tree.Tree;

import java.util.Collections;
import java.util.List;

//规则元数据
@Rule(
        key = "MyFirstCustomCheck",
        name = "参数类型和返回值类型不能相同",
        description = "但一个方法只有一个参数时，参数类型和返回值类型不应该相同.",
        priority = Priority.CRITICAL,
        tags = {"bug"})
public class MyFirstCustomCheck extends IssuableSubscriptionVisitor {

    @Override
    public List<Tree.Kind> nodesToVisit() {
        // 规则分析目标，可以是多了，这里以检测方法为例
        return Collections.singletonList(Tree.Kind.METHOD);
    }

    @Override
    public void visitNode(Tree tree) {
        // 取得方法
        MethodTree method = (MethodTree) tree;
        //包含1个参数
        if (method.parameters().size() == 1) {
            Symbol.MethodSymbol symbol = method.symbol();
            //参数类型
            Type firstParameterType = symbol.parameterTypes().get(0);
            //返回值类型
            Type returnType = symbol.returnType().type();
            //参数类型和返回值类型相同
            if (returnType.is(firstParameterType.fullyQualifiedName())) {
                //报告争议
                reportIssue(method.simpleName(), "不要这么做!");
            }
        }
    }

}